package com.lxy.controller.Admin;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxy.common.BaseContext;
import com.lxy.common.R;
import com.lxy.constant.CodeConstant;
import com.lxy.constant.JwtClaimsConstant;
import com.lxy.constant.OperationConstant;
import com.lxy.dto.*;
import com.lxy.entity.*;
import com.lxy.properties.JwtProperties;
import com.lxy.service.*;
import com.lxy.utils.JwtUtil;
import com.lxy.utils.ValidateCodeUtils;
import com.lxy.vo.AdminLoginVO;
import com.lxy.vo.LocationVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private JavaMailSenderImpl mailSender;
    @Autowired
    private BusinessManService businessManService;
    @Autowired
    private OperationService operationService;
    @Autowired
    private ShopService shopService;
    @Autowired
    private RiderService riderService;
    @Autowired
    private UserService userService;
    @Autowired
    private RiderPlaceService riderPlaceService;
    @Autowired
    private RiderAccountService riderAccountService;
    private String ak="wUO6QkgZ21Db6nOR1QdvbAzphr9omiSV";

    /**
     * 获取ip地址
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = null;
        //X-Forwarded-For：Squid 服务代理
        String ipAddresses = request.getHeader("X-Forwarded-For");
        System.out.println("====ipAddresses:"+ipAddresses);
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            //打印所有头信息
            String s = headerNames.nextElement();
            String header = request.getHeader(s);
            System.out.println(s+"::::"+header);
        }
        System.out.println("headerNames:"+ JSON.toJSONString(headerNames));
        System.out.println("RemoteHost:"+request.getRemoteHost());
        System.out.println("RemoteAddr:"+request.getRemoteAddr());

        String unknown = "unknown";
        if (ipAddresses == null || ipAddresses.length() == 0 || unknown.equalsIgnoreCase(ipAddresses)) {
            //Proxy-Client-IP：apache 服务代理
            ipAddresses = request.getHeader("Proxy-Client-IP");
        }

        if (ipAddresses == null || ipAddresses.length() == 0 || unknown.equalsIgnoreCase(ipAddresses)) {
            //WL-Proxy-Client-IP：weblogic 服务代理
            ipAddresses = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ipAddresses == null || ipAddresses.length() == 0 || unknown.equalsIgnoreCase(ipAddresses)) {
            //HTTP_CLIENT_IP：有些代理服务器
            ipAddresses = request.getHeader("HTTP_CLIENT_IP");
        }

        if (ipAddresses == null || ipAddresses.length() == 0 || unknown.equalsIgnoreCase(ipAddresses)) {
            //X-Real-IP：nginx服务代理
            ipAddresses = request.getHeader("X-Real-IP");
        }

        //有些网络通过多层代理，那么获取到的ip就会有多个，一般都是通过逗号（,）分割开来，并且第一个ip为客户端的真实IP
        if (ipAddresses != null && ipAddresses.length() != 0) {
            ip = ipAddresses.split(",")[0];
        }

        //还是不能获取到，最后再通过request.getRemoteAddr();获取
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ipAddresses)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }





    /**
     * 发送email
     */
    public void sendEmail(String email,String title,String text) throws Exception {
        try{
            //给用户发消息
            SimpleMailMessage mailMessage = new SimpleMailMessage(); //创建一个邮件信息
            System.out.println("当前时间" + new Date());
            mailMessage.setSubject(title);//邮件的主题
            mailMessage.setText(text);//邮件的内容
            mailMessage.setTo(email);//接收者的邮箱
            mailMessage.setFrom("3319725459@qq.com");//发送者的邮箱
            mailSender.send(mailMessage);//发送邮件
        }catch (Exception e){
            throw new Exception("邮箱错误，请检查邮箱填写是否正确");
        }
    }

    /**
     * 添加操作记录
     */
    public void addOperation(String name,String email,String type,String reason){
        //添加操作记录
        Operation operation=new Operation();
        operation.setAdminId(BaseContext.getCurrentId());
        operation.setName(name);
        operation.setEmail(email);
        operation.setTime(LocalDateTime.now());
        operation.setType(type);
        operation.setReason(reason);
        //添加管理员姓名
        Admin admin = adminService.getById(BaseContext.getCurrentId());
        operation.setAdminName(admin.getName());
        operationService.save(operation);
    }


    /**
     * 管理员登录
     * @param loginDTO
     * @return
     */
    @ApiOperation("管理员登录")
    @PostMapping("/login")
    public R<AdminLoginVO> login(@RequestBody LoginDTO loginDTO){
        //判断账户是否存在
        String account = loginDTO.getAccount();
        LambdaQueryWrapper<Admin> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Admin::getAccount,account);
        Admin admin = adminService.getOne(lambdaQueryWrapper);
        if(admin==null){
            return R.error("账户不存在，请先注册");
        }
        //账户存在，判断密码是否正确
        String correctPassword = admin.getPassword();
        String password = DigestUtils.md5DigestAsHex(loginDTO.getPassword().getBytes());
        if(!Objects.equals(password, correctPassword)){
            return R.error("账号或密码错误，请重试");
        }
        //判断账户是否被禁用
        Integer banded = admin.getBanded();
        if(banded==0){
            return R.error("账户被禁用，如有疑惑请联系xxxxx");
        }
        //判断账户是否被审核
        Integer status = admin.getStatus();
        if(status==0){
            return  R.error("请等待审核");
        }
        //登录成功，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, admin.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        AdminLoginVO adminLoginVO=new AdminLoginVO();
        adminLoginVO.setToken(token);
        adminLoginVO.setAdmin(admin);
        return R.success(adminLoginVO);
    }

    /**
     * 管理员注册功能
     * @param registrationDTO
     * @return
     */
    @ApiOperation("管理员注册")
    @PostMapping("/registration")
    public R registration(@RequestBody RegistrationDTO registrationDTO){
        //判断账号是否重复
        String account = registrationDTO.getAccount();
        LambdaQueryWrapper<Admin> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Admin::getAccount,account);
        Admin one = adminService.getOne(lambdaQueryWrapper);
        if(one!=null){
            return R.error("账号名重复");
        }
        //判断电话号码是否重复
        String phone = registrationDTO.getPhone();
        lambdaQueryWrapper.clear();
        lambdaQueryWrapper.eq(Admin::getPhone,phone);
        Admin one1 = adminService.getOne(lambdaQueryWrapper);
        if(one1!=null){
            return R.error("电话号码重复，请更换电话号码");
        }
        //判断邮箱是否重复
        String email = registrationDTO.getEmail();
        lambdaQueryWrapper.clear();
        lambdaQueryWrapper.eq(Admin::getEmail,email);
        Admin getByEmail = adminService.getOne(lambdaQueryWrapper);
        if(getByEmail!=null){
            //邮箱重复
            return R.error("邮箱已注册，请勿重复注册");
        }
        //判断redis中存储的验证码和用户输入的验证码是否相同
        ValueOperations valueOperations=redisTemplate.opsForValue();
        Integer rCode = (Integer)valueOperations.get(email+ CodeConstant.ADMIN_REGISTRATION);
        if(!Objects.equals(rCode, registrationDTO.getCode())){
            //验证码错误
            return R.error("验证码错误");
        }
        //验证成功后，删除redis缓存
        redisTemplate.delete(CodeConstant.ADMIN_REGISTRATION);
        //创建admin用户，但是status设为0
        Admin admin =new Admin();
        admin.setAccount(registrationDTO.getAccount());
        String password = DigestUtils.md5DigestAsHex(registrationDTO.getPassword().getBytes());
        admin.setPassword(password);
        admin.setEmail(registrationDTO.getEmail());
        admin.setName(registrationDTO.getName());
        //没有sex
        admin.setIdNumber(registrationDTO.getIdNumber());
        admin.setCreateTime(LocalDateTime.now());
        admin.setPhone(registrationDTO.getPhone());
        //将状态设置为0，表示等待管理员审核
        admin.setStatus(0);
        admin.setBanded(1);
        //存储用户
        adminService.save(admin);
        return R.success("提交成功,将在七个工作日内审核");
    }


    /**
     * 超级管理员查看所有普通管理员申请(超级管理员专用)分页查询
     */
    @ApiOperation(("超级管理员查看所有普通管理员申请"))
    @GetMapping("/viewApplication")
    public R<Page<Admin>> audit(int page, int pageSize,String name,String email){
        Page<Admin> pageInfo=new Page<>(page,pageSize);
        LambdaQueryWrapper<Admin> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Admin::getStatus,0);
        lambdaQueryWrapper.like(name!=null,Admin::getName,name);
        lambdaQueryWrapper.eq(email!=null,Admin::getEmail,email);
        adminService.page(pageInfo,lambdaQueryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 同意管理员申请
     * @return
     */
    @GetMapping("/agree/{id}")
    @ApiOperation("超级管理员同意管理员申请")
    public R<String> agree(@PathVariable Long id) throws Exception {
        //获取到了要审核的管理员申请id，根据id修改status
        Admin admin = adminService.getById(id);
        //将该管理员的status改为1
        admin.setStatus(1);
        adminService.updateById(admin);
        //给用户发消息
        String text="感谢您对本软件的支持："+admin.getName()+"现在可以使用飞鸟跑腿后台管理系统";
        sendEmail(admin.getEmail(),"飞鸟跑腿APP",text);
//        SimpleMailMessage mailMessage = new SimpleMailMessage(); //创建一个邮件信息
//        System.out.println("当前时间" + new Date());
//        mailMessage.setSubject("已通过您的申请");//邮件的主题
//        mailMessage.setText("感谢您对本软件的支持："+admin.getName()+"现在可以使用飞鸟跑腿后台管理系统");//邮件的内容 TODO 更改样式
//        mailMessage.setTo(admin.getEmail());//接收者的邮箱
//        mailMessage.setFrom("3319725459@qq.com");//发送者的邮箱
//        mailSender.send(mailMessage);//发送邮件
        //添加操作记录
        addOperation(admin.getName(), admin.getEmail(),OperationConstant.AGREE_ADMIN,null);
        return R.success("审核成功");
    }

    /**
     * 拒绝申请
     */
    @ApiOperation(("超级管理员拒绝管理员申请"))
    @PostMapping("/disAgree")
    public R<String> disAgree(@RequestBody OperationReasonDTO operationReasonDTO){
        //获取到了要审核的管理员申请id，根据id修改status
        Admin admin = adminService.getById(operationReasonDTO.getId());
        //给用户发消息
        SimpleMailMessage mailMessage = new SimpleMailMessage(); //创建一个邮件信息
        System.out.println("当前时间" + new Date());
        mailMessage.setSubject("审核失败");//邮件的主题
        mailMessage.setText("您的申请被拒绝："+admin.getName()+"如有疑惑请联系xxxxxx");//邮件的内容 TODO 更改样式
        mailMessage.setTo(admin.getEmail());//接收者的邮箱
        mailMessage.setFrom("3319725459@qq.com");//发送者的邮箱
        mailSender.send(mailMessage);//发送邮件
        //拒绝该申请后删除这条申请记录对应的管理员信息
        adminService.removeById(admin);
        //添加操作记录
        addOperation(admin.getName(), admin.getEmail(), OperationConstant.REFUSE_ADMIN, operationReasonDTO.getReason());
        return R.success("拒绝成功");
    }

    /**
     * 超级管理员禁用管理员账户
     * @param operationReasonDTO
     * @return
     */
    @ApiOperation("超级管理员禁用管理员账户")
    @PostMapping("/band")
    public R<String> band(@RequestBody OperationReasonDTO operationReasonDTO){
        Admin admin = adminService.getById(operationReasonDTO.getId());
        admin.setBanded(0);
        adminService.updateById(admin);
        //给用户发消息
        SimpleMailMessage mailMessage = new SimpleMailMessage(); //创建一个邮件信息
        System.out.println("当前时间" + new Date());
        mailMessage.setSubject("您的账号被禁用");//邮件的主题
        mailMessage.setText("您的账号于"+LocalDateTime.now()+"被禁用："+admin.getName()+"如有疑惑请联系xxxxxx");//邮件的内容 TODO 更改样式
        mailMessage.setTo(admin.getEmail());//接收者的邮箱
        mailMessage.setFrom("3319725459@qq.com");//发送者的邮箱
        mailSender.send(mailMessage);//发送邮件
        //添加操作记录
        addOperation(admin.getName(), admin.getEmail(), OperationConstant.BAN_ADMIN, operationReasonDTO.getReason());
        return R.success("禁用账户成功");
    }

    /**
     * 超级管理员启用管理员账户
     * @param id
     * @return
     */
    @ApiOperation("超级管理员启用管理员账户")
    @GetMapping("/unBand/{id}")
    public R<String> unBand(@PathVariable Long id){
        Admin admin = adminService.getById(id);
        admin.setBanded(1);
        adminService.updateById(admin);
        //给用户发消息
        SimpleMailMessage mailMessage = new SimpleMailMessage(); //创建一个邮件信息
        System.out.println("当前时间" + new Date());
        mailMessage.setSubject("您的账号被启用");//邮件的主题
        mailMessage.setText("您的账号于"+LocalDateTime.now()+"被启用："+admin.getName()+"如有疑惑请联系xxxxxx");//邮件的内容 TODO 更改样式
        mailMessage.setTo(admin.getEmail());//接收者的邮箱
        mailMessage.setFrom("3319725459@qq.com");//发送者的邮箱
        mailSender.send(mailMessage);//发送邮件
        //添加操作记录
        addOperation(admin.getName(), admin.getEmail(), OperationConstant.UNBAN_ADMIN, null);
        return R.success("启用账户成功");
    }

    /**
     * 超级管理员查看所有管理员(分页查询)、模糊查询name、查询手机号
     * @return
     */
    @ApiOperation("超级管理员查看所有管理员(分页查询)、模糊查询name、查询手机号")
    @GetMapping("/showAllAdmin")
    public R<Page> showAllAdmin(int page,int pageSize,String name,String sortByCreateTime,String phone,Integer banded,String sex){
        Page<Admin> pageInfo=new Page<>(page,pageSize);
        LambdaQueryWrapper<Admin> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        //首先得是审核通过的
        lambdaQueryWrapper.eq(Admin::getStatus,1L);
        lambdaQueryWrapper.like(name!=null,Admin::getName,name);
        lambdaQueryWrapper.eq(phone!=null,Admin::getPhone,phone);
        lambdaQueryWrapper.eq(banded!=null,Admin::getBanded,banded);
        lambdaQueryWrapper.eq(sex!=null,Admin::getSex,sex);
        if(sortByCreateTime==null){
            lambdaQueryWrapper.orderByDesc(Admin::getCreateTime);
        } else if(sortByCreateTime.equals("asc")){
            lambdaQueryWrapper.orderByAsc(Admin::getCreateTime);
        }else{
            lambdaQueryWrapper.orderByDesc(Admin::getCreateTime);
        }
        adminService.page(pageInfo,lambdaQueryWrapper);
        return R.success(pageInfo);
    }

//    /**
//     * 查看所有商家申请请求
//     */
//    @ApiOperation("查看所有商家申请请求")
//    @GetMapping("/showAllBusinessManApplication")
//    public R<List<BusinessMan>> showAllBusinessManApplication(){
//        //找出所有status==0的老板
//        LambdaQueryWrapper<BusinessMan> lambdaQueryWrapper=new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.eq(BusinessMan::getStatus,0);
//        List<BusinessMan> list = businessManService.list(lambdaQueryWrapper);
//        return R.success(list);
//    }
//
//    /**
//     * 同意商家的注册申请
//     */
//    @ApiOperation("同意商家的注册申请")
//    @GetMapping("/agreeB/{id}")
//    public R<String> agreeB(@PathVariable Long id){
//        BusinessMan businessMan = businessManService.getById(id);
//        businessMan.setStatus(1);
//        businessManService.updateById(businessMan);
//        //发送信息到老板的邮箱中
//        String email=businessMan.getEmail();
//        String title="您的商家申请已通过";
//        String text="感谢您对本软件的支持："+businessMan.getName()+" 您的商家申请已通过";
//        sendEmail(email,title,text);
//        //添加操作记录
//        addOperation(businessMan.getName(),email,OperationConstant.AGREE_BUSINESSMAN,null);
//        return R.success("已同意申请");
//    }
//
//    /**
//     *拒绝商家的注册申请
//     * @return
//     */
//    @ApiOperation("拒绝商家的注册申请")
//    @PostMapping("/disAgreeB")
//    public R<String> disAgreeB(@RequestBody OperationReasonDTO operationReasonDTO){
//        //删除对应的老板数据
//        BusinessMan businessMan = businessManService.getById(operationReasonDTO.getId());
//        String email = businessMan.getEmail();
//        String name = businessMan.getName();
//        businessManService.removeById(businessMan);
//        String title="您的商家申请被拒绝";
//        String text="您的商家申请被拒绝:"+name+" 如有疑惑请联系xxxxx";
//        sendEmail(email,title,text);
//        //添加操作记录
//        addOperation(businessMan.getName(),businessMan.getEmail(),OperationConstant.REFUSE_BUSINESSMAN, operationReasonDTO.getReason());
//        return R.success("拒绝申请成功");
//    }

    /**
     * 忘记密码（管理员）
     */
    @ApiOperation("忘记密码（管理员）")
    @PostMapping("/forget")
    public R forget(@RequestBody ForgetDTO forgetDTO){
        String email = forgetDTO.getEmail();
        //先判断
        Integer code = forgetDTO.getCode();
        //查找对应的admin数据
        LambdaQueryWrapper<Admin> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Admin::getEmail,email);
        Admin admin = adminService.getOne(lambdaQueryWrapper);
        //判断账号是否正常
        if(admin.getStatus()==0){
            return R.error("该账号还在审核中");
        }else if(admin.getBanded()==0){
            return R.error("账号被禁用");
        }
        ValueOperations valueOperations = redisTemplate.opsForValue();
        Integer Rcode = (Integer)valueOperations.get(email+CodeConstant.ADMIN_FORGET);
        if(!Objects.equals(Rcode, code)){
            return R.error("验证码错误，请重试");
        }
        //验证码正确,删除redis缓存
        redisTemplate.delete(email+CodeConstant.ADMIN_FORGET);
        //更新新密码
        String password = DigestUtils.md5DigestAsHex(forgetDTO.getPassword().getBytes());
        admin.setPassword(password);
        adminService.updateById(admin);
        return R.success("找回密码成功");
    }


    /**
     * 根据id查询管理员信息
     * @param id
     * @return
     */
    @ApiOperation("根据id查询管理员信息")
    @GetMapping("/getById")
    public R<Admin> getById(Long id){
        Admin admin = adminService.getById(id);
        return R.success(admin);
    }

    /**
     * 查看管理员自己的操作记录（分页）
     * @return
     */
    @ApiOperation("查看管理员自己的操作记录(分页)")
    @GetMapping("/userOperation")
    public R<Page<Operation>> userOperation(int page,int pageSize,String type,String sortByCreateTime, String name){
        Long adminId = BaseContext.getCurrentId();
        Page<Operation> pageInfo=new Page<>(page,pageSize);
        LambdaQueryWrapper<Operation> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(type!=null,Operation::getType,type);
        lambdaQueryWrapper.like(name!=null,Operation::getName,name);
        if(sortByCreateTime==null){
            lambdaQueryWrapper.orderByDesc(Operation::getTime);
        }else if(sortByCreateTime.equals("asc")){
            lambdaQueryWrapper.orderByAsc(Operation::getTime);
        }else {
            lambdaQueryWrapper.orderByDesc(Operation::getTime);
        }
        if(adminId==1){
            //该用户是超级管理员，可以查看所有操作记录
            operationService.page(pageInfo,lambdaQueryWrapper);
            return R.success(pageInfo);
        }
        lambdaQueryWrapper.eq(Operation::getAdminId,adminId);
        operationService.page(pageInfo,lambdaQueryWrapper);
        return R.success(pageInfo);
    }


    /**
     * 根据id查看店铺全部信息
     */
    @ApiOperation("根据id查看店铺全部信息")
    @GetMapping("/getShopById/{id}")
    public R<Shop> getShopById(@PathVariable Long id){
        Shop shop = shopService.getById(id);
        return R.success(shop);
    }

    /**
     * 查看所有店铺申请和所有店铺(分页)
     */
    @ApiOperation("查看所有店铺申请和所有店铺(分页)")
    @GetMapping("/viewApplicationShop")
    public R<Page<Shop>> viewApplicationShop(int page,int pageSize,String sortByCreateTime,String shopName,Integer banded,Integer status){
        Page<Shop> pageInfo=new Page<>(page,pageSize);
        LambdaQueryWrapper<Shop> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(shopName!=null,Shop::getShopName,shopName);
        lambdaQueryWrapper.eq(banded!=null,Shop::getBanded,banded);
        lambdaQueryWrapper.eq(status!=null,Shop::getStatus,status);
        if(sortByCreateTime==null){
            lambdaQueryWrapper.orderByDesc(Shop::getCreateTime);
        }else if(sortByCreateTime.equals("asc")){
            lambdaQueryWrapper.orderByAsc(Shop::getCreateTime);
        }else {
            lambdaQueryWrapper.orderByDesc(Shop::getCreateTime);
        }
        shopService.page(pageInfo,lambdaQueryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 管理员对店铺注册申请的操作
     */
    @ApiOperation("管理员对店铺注册申请的操作")
    @PostMapping("/shopOperation")
    public R<String> shopOperation(@RequestBody OperationReasonDTO operationReasonDTO) throws Exception {
        int isAgree = operationReasonDTO.getIsAgree();
        Shop shop = shopService.getById(operationReasonDTO.getId());
        //添加操作记录
        Operation operation=new Operation();
        operation.setAdminId(BaseContext.getCurrentId());
        operation.setName(shop.getName());
        operation.setEmail(shop.getEmail());
        operation.setTime(LocalDateTime.now());
        String title="请查看您的审核结果";
        String text="";
        if(isAgree==1){
            //表示同意申请,将status改为1
            shop.setStatus(1);
            shopService.updateById(shop);
            operation.setType(OperationConstant.AGREE_SHOP);
            //编辑信息
            text="感谢您对本软件的支持："+shop.getShopName()+" 您的店铺审核已通过";
        }else {
            //表示拒绝，删除这条记录
            shopService.removeById(shop);
            operation.setType(OperationConstant.REFUSE_SHOP);
            operation.setReason(operationReasonDTO.getReason());
            //编辑信息
            text="您的店铺申请已被拒绝："+shop.getShopName()+"如有疑惑请联系管理员xxx";
        }
        //添加管理员姓名
        Admin admin = adminService.getById(BaseContext.getCurrentId());
        operation.setAdminName(admin.getName());
        operationService.save(operation);
        //给商家发信息
        sendEmail(shop.getEmail(),title,text);
        return R.success("操作成功");
    }
    /**
     * 退出
     * @return
     */
    @ApiOperation("管理员登出")
    @PostMapping("/logout")
    public R<String> logout() {
        return R.success("退出成功");
    }

    /**
     * 查看所有骑手和骑手申请(分页查询)
     */
    @ApiOperation("查看所有骑手和骑手申请(分页查询)")
    @GetMapping("/viewAllRider")
    public R<Page<Rider>> viewAllRider(int page,int pageSize,String sortByCreateTime,String name,Integer banded,Integer status){
        Page<Rider> pageInfo=new Page<>(page,pageSize);
        LambdaQueryWrapper<Rider> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(status!=null,Rider::getStatus,status);
        lambdaQueryWrapper.like(name!=null,Rider::getName,name);
        lambdaQueryWrapper.eq(banded!=null,Rider::getBanded,banded);
        if(sortByCreateTime==null){
            lambdaQueryWrapper.orderByDesc(Rider::getCreateTime);
        }else if(sortByCreateTime.equals("asc")){
            lambdaQueryWrapper.orderByAsc(Rider::getCreateTime);
        }else {
            lambdaQueryWrapper.orderByDesc(Rider::getCreateTime);
        }
        riderService.page(pageInfo,lambdaQueryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 对骑手的注册审核
     */
    @ApiOperation("对骑手的注册审核")
    @PostMapping("/riderOperation")
    public R<String> riderOperation(@RequestBody OperationReasonDTO operationReasonDTO) throws Exception {
        int isAgree = operationReasonDTO.getIsAgree();
        Rider rider = riderService.getById(operationReasonDTO.getId());
        //添加操作记录
        Operation operation=new Operation();
        operation.setAdminId(BaseContext.getCurrentId());
        operation.setName(rider.getName());
        operation.setEmail(rider.getEmail());
        operation.setTime(LocalDateTime.now());
        String title="请查看您的审核结果";
        String text="";
        if(isAgree==1){
            //表示同意申请,将status改为1
            rider.setStatus(1);
            riderService.updateById(rider);
            //
            operation.setType(OperationConstant.AGREE_RIDER);
            //编辑信息
            text="感谢您对本软件的支持："+rider.getName()+" 您的骑手审核已通过";
        }else {
            //表示拒绝，删除这条记录
            riderService.removeById(rider);
            operation.setType(OperationConstant.REFUSE_RIDER);
            operation.setReason(operationReasonDTO.getReason());
            //删除rider_place数据
            LambdaQueryWrapper<RiderPlace> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(RiderPlace::getRiderId,rider.getId());
            riderPlaceService.remove(lambdaQueryWrapper);
            //编辑信息
            text="您的骑手申请已被拒绝："+rider.getName()+"如有疑惑请联系管理员xxx";
            //删除riderAccount数据
            LambdaQueryWrapper<RiderAccount> lambdaQueryWrapper1=new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(RiderAccount::getRiderId,rider.getId());
            riderAccountService.remove(lambdaQueryWrapper1);
        }
        //添加管理员姓名
        Admin admin = adminService.getById(BaseContext.getCurrentId());
        operation.setAdminName(admin.getName());
        operationService.save(operation);
        //给骑手发信息
        sendEmail(rider.getEmail(),title,text);
        return R.success("操作成功");
    }

    /**
     * 根据id查看骑手所有信息
     */
    @ApiOperation("根据id查看骑手所有信息")
    @GetMapping("/getRiderById/{id}")
    public R<Rider> getRiderById(@PathVariable Long id){
        Rider rider = riderService.getById(id);
        return R.success(rider);
    }

    /**
     * 查看所有用户(分页查询)
     */
    @ApiOperation("查看所有用户")
    @GetMapping("/viewAllUser")
    public R<Page<User>> viewAllUser(int page,int pageSize,String sortByCreateTime,String name,Integer banded){
        Page<User> pageInfo=new Page<>(page,pageSize);
        LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(name!=null,User::getName,name);
        lambdaQueryWrapper.eq(banded!=null,User::getBanded,banded);
        if(sortByCreateTime==null){
            lambdaQueryWrapper.orderByDesc(User::getCreateTime);
        }else if(sortByCreateTime.equals("asc")){
            lambdaQueryWrapper.orderByAsc(User::getCreateTime);
        }else {
            lambdaQueryWrapper.orderByDesc(User::getCreateTime);
        }
        userService.page(pageInfo,lambdaQueryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 根据id查看用户的所有信息
     */
    @ApiOperation("根据id查看用户所有信息")
    @GetMapping("/getUserById/{id}")
    public R<User> getUserById(@PathVariable Long id){
        User user = userService.getById(id);
        return R.success(user);
    }

    /**
     * 对骑手的禁用启用
     */
    @ApiOperation("对骑手的禁用启用")
    @PostMapping("/riderChangeBanded")
    public R<String> riderChangeBanded(@RequestBody BanOperationDTO banOperationDTO) throws Exception {
        Rider rider = riderService.getById(banOperationDTO.getId());
        rider.setBanded(banOperationDTO.getBanded());
        riderService.updateById(rider);
        //添加操作记录
        String text="";
        if(banOperationDTO.getBanded()==1){
            //启用账号
            addOperation(rider.getName(),rider.getEmail(),OperationConstant.UNBAN_RIDER,null);
            text="您的骑手账号被启用："+rider.getName();
        }else{
            //禁用账号
            addOperation(rider.getName(),rider.getEmail(),OperationConstant.BAN_RIDER, banOperationDTO.getReason());
            text="您的骑手账号被禁用"+rider.getName()+" 如有疑惑，请联系xxx";
        }
        //给骑手发消息
        sendEmail(rider.getEmail(),"飞鸟跑腿APP",text);
        return R.success("操作成功");
    }

    /**
     * 对店铺的禁用启用
     */
    @ApiOperation("对店铺的禁用启用")
    @PostMapping("/shopChangeBanded")
    public R<String> shopChangeBanded(@RequestBody BanOperationDTO banOperationDTO) throws Exception {
        Shop shop = shopService.getById(banOperationDTO.getId());
        shop.setBanded(banOperationDTO.getBanded());
        shopService.updateById(shop);
        //添加操作记录
        String text="";
        if(banOperationDTO.getBanded()==1){
            //启用账号
            addOperation(shop.getName(),shop.getEmail(),OperationConstant.UNBAN_SHOP,null);
            text="您的店铺"+shop.getShopName()+"被启用："+shop.getName();
        }else{
            //禁用账号
            addOperation(shop.getName(),shop.getEmail(),OperationConstant.BAN_SHOP, banOperationDTO.getReason());
            text="您的商铺"+shop.getShopName()+"被禁用"+shop.getName()+" 如有疑惑，请联系xxx";
        }
        //给骑手发消息
        sendEmail(shop.getEmail(),"飞鸟跑腿APP",text);
        return R.success("操作成功");
    }

    /**
     * 对用户的禁用启用
     */
    @ApiOperation("对用户的禁用启用")
    @PostMapping("/userChangeBanded")
    public R<String> userChangeBanded(@RequestBody BanOperationDTO banOperationDTO) throws Exception {
        User user = userService.getById(banOperationDTO.getId());
        user.setBanded(banOperationDTO.getBanded());
        userService.updateById(user);
        //添加操作记录
        String text="";
        if(banOperationDTO.getBanded()==1){
            //启用账号
            addOperation(user.getName(),user.getEmail(),OperationConstant.UNBAN_USER,null);
            text="您的账号“"+user.getAccount()+"”被启用："+user.getName();
        }else{
            //禁用账号
            addOperation(user.getName(),user.getEmail(),OperationConstant.BAN_USER, banOperationDTO.getReason());
            text="您的账号“"+user.getAccount()+"”被禁用："+user.getName()+" 如有疑惑，请联系xxx";
        }
        //给骑手发消息
        sendEmail(user.getEmail(),"飞鸟跑腿APP",text);
        return R.success("操作成功");
    }

    /**
     * 根据ip获取管理员当前位置
     */
    @ApiOperation("根据ip获取管理员当前位置")
    @GetMapping("/getLocation")
    public R<LocationVO> getLocation(HttpServletRequest request){
        //获取设备ip地址
        String ip = getIpAddress(request);
        //测试用例
//        String ip="111.206.214.37";
        if(ip==null){
            return R.error("获取位置失败");
        }
        //调用接口发送get请求获取经纬度
        String url="https://api.map.baidu.com/location/ip?ip={}&coor=bd09ll&ak={}";
        url= StrUtil.format(url,ip,ak);
        //发起get请求
        String body = HttpRequest.get(url).execute().body();
        GetLocationByIpDTO getLocationByIpDTO = JSON.parseObject(body, GetLocationByIpDTO.class);
        if(getLocationByIpDTO.getStatus()!=0){
            return R.error("获取位置失败，请检查网络");
        }
        LocationVO locationVO=new LocationVO();
        //返回经纬度（城市中心的）
        locationVO.setLongitude(getLocationByIpDTO.getContent().getPoint().getX());
        locationVO.setLatitude(getLocationByIpDTO.getContent().getPoint().getY());
        return R.success(locationVO);
    }





















}
